﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;

namespace BrainTechLLC.Silverlight.ClientApplication.Controls
{
    public partial class MapSquare : UserControl
    {
        public static readonly DependencyProperty GraphicUriProperty = DependencyProperty.Register(
            "GraphicUri",
            typeof(Uri),
            typeof(MapSquare),
            new PropertyMetadata(new Uri("/FloppyDriveSearch.png", UriKind.Relative), new PropertyChangedCallback(GraphicUriChanged)));

        public Uri GraphicUri
        {
            get { return (Uri)GetValue(GraphicUriProperty); }
            set { SetValue(GraphicUriProperty, value); }
        }

        public GameLocation Location
        {
            get;
            set;
        }

        private static void GraphicUriChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MapSquare t = (MapSquare)d;
            t.GraphicUri = e.NewValue as Uri;
            t.Dispatcher.BeginInvoke(() => t.UpdateUri());
        }

        public void UpdateUri()
        {
            Uri uri = GraphicUri;
            
            if (uri == null)
                return;

            img.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(img_ImageFailed);
            var bitmap = new BitmapImage(uri);
            bitmap.DownloadProgress += new EventHandler<DownloadProgressEventArgs>(bitmap_DownloadProgress);
            img.Source = bitmap;
            
        }

        void bitmap_DownloadProgress(object sender, DownloadProgressEventArgs e)
        {
            if (e.Progress == 1)
            {
                BitmapImage bitmap = sender as BitmapImage;
                img.ImageFailed -= img_ImageFailed;
                bitmap.DownloadProgress -= bitmap_DownloadProgress;
            }
        }

        void img_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            Dispatcher.BeginInvoke(()=>MessageBox.Show(e.ErrorException.ToString()));
        }
        
        public MapSquare()
        {
            // Required to initialize variables
            InitializeComponent();
        }
    }
}